<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2007-2008 Starbugs (univis2typo3@googlegroups.com)
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*  A copy is found in the textfile GPL.txt and important notices to the license
*  from the author is found in LICENSE.txt distributed with these scripts.
*
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * Module: Web>UnivIS2Typo3
 *
 * Description:
 *
 * Notice: 
 *
 *  
 * @author	Starbugs <univis2typo3@googlegroups.com>
 */

require_once($BACK_PATH.'template.php');

class ConfigurationEditOrderTable
{
    var $id = 0;
    //var $content;
    var $template;
    var $sectionName_;
    var $itemType_;
    var $table_;
    var $BACK_PATH = '../../../../typo3/';

    function renderContent($id) {			
	$this->template = new Template();
	$this->template->table_TABLE = '<table border="1" cellspacing="0" cellpadding="3" id="typo3-tmpltable">';

	$this->id = $id;		
	$this->itemType_    = $_REQUEST['item'];
	$this->table_ = "tx_u2t3_{$this->sectionName_}_{$this->itemType_}_order";

	switch (@$_REQUEST['action'])
	{
	    case 'edit':
		return $this->renderEditForm();
		break;
	    case 'edit_save':
		$this->saveEditForm();
		break;
	    case 'up':
	    case 'down':
		$this->handleSort();
		break;
	    case 'hide':
		$this->handleHide();
		break;
	    default:
		// do nothing, render list
		break;
	}
	return $this->renderList();
    }

    function saveEditForm() {
	$query = "UPDATE `{$this->table_}`"
		. " SET `description` = '{$_REQUEST['description']}', `description_en` = '{$_REQUEST['description_en']}'"
		. " WHERE `uid` = {$_REQUEST['key']}";
	performSQLQuery($query, false);
    }

    function renderEditForm() {
	$content = '';
	$output = '';

	$selection	= "DISTINCT `uid`, `{$this->itemType_}`, `hidden`, `sorting`, `description`, `description_en`";
	$from	= "`tx_u2t3_{$this->sectionName_}_{$this->itemType_}_order`";
	$where	= "`uid` = {$_REQUEST['key']}";
	$groupby	= "";
	$orderby	= "`sorting`";
	$limit	= "";

	$query = $GLOBALS['TYPO3_DB']->SELECTquery(
		$selection,			// SELECT
		$from,			// FROM
		$where,			// WHERE
		$groupby,	    		// GROUP BY
		$orderby,			// ORDER BY
		$limit			// LIMIT
	);
	$res = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
	$row = mysql_fetch_assoc($res); 
			

	$content .= '<form action="" method="post">';
	$content .= "<input type='hidden' name='id'   value='{$_REQUEST['id']}' />";
	$content .= "<input type='hidden' name='item' value='{$_REQUEST['item']}' />";
	$content .= "<input type='hidden' name='key'  value='{$_REQUEST['key']}' />";
	$content .= "<input type='hidden' name='action' value='edit_save' />";
	$content .= "<h2>Edit: {$this->sectionName_} {$this->itemType_}</h2>";
	$content .= "<h3>".ucfirst($this->itemType_)." ID: {$row[ $this->itemType_ ]}</h3>";
	$content .= "<label for='de'>Deutsch:  <input id='de' name='description'    value='{$row['description']}'    /></label><br />";
	$content .= "<label for='en'>Englisch: <input id='en' name='description_en' value='{$row['description_en']}' /></label><br />";
	$content .= '<br />';
	$content .= '<input type="submit" value="Speichern" />';
	$content .= '</form>';


	$content .= '<br />'.$output;
	return $content;
    }

    function renderList() {
	return 'Override me!';
    }

    /**
     * @param $id int
     * @param $sectionName_ string e.g. theses/publications/etc
     * @param $itemType_ string e.g. type/status/etc
     */
    function getListItems($itemType_)
    {
	$selection	= "DISTINCT `uid`, `{$itemType_}`, `hidden`, `sorting`, `description`, `description_en`";
	$from	= "`tx_u2t3_{$this->sectionName_}_{$itemType_}_order`";
	$where	= "";

	$groupby	= "";
	$orderby	= "`sorting`";
	$limit	= "";

	$query = $GLOBALS['TYPO3_DB']->SELECTquery(
		$selection,			// SELECT
		$from,			// FROM
		$where,			// WHERE
		$groupby,	    		// GROUP BY
		$orderby,			// ORDER BY
		$limit			// LIMIT
	);
	$res = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
	$out = array ();

	$out[] = array('', '', '', '<b>'.ucfirst($itemType_).'</b>', 'Deutsch', 'English', '&nbsp;');
	while ($row = mysql_fetch_assoc($res))
	{
	    $out[] = $this->createTableRow($itemType_, $row[$itemType_], $row);
	}		
			
	return $out;
    }


    /**
     * @param $id_ int
     * @param $title_ string
     * @param $row_ array
     */
    function createTableRow($type_, $title_, $row_) {
	    $image_up   = $this->getButton('button_up');
	    $image_down = $this->getButton('button_down');
	    $image_hide = $this->getButton('button_'. (0==$row_['hidden'] ? 'hide' : 'unhide') );
	    $image_edit = $this->getButton('edit2');

	$up   = "<b><a href='?id={$this->id}&item={$type_}&key={$row_['uid']}&action=up&sorting={$row_['sorting']}'>{$image_up}</a></b>";
	$down = "<b><a href='?id={$this->id}&item={$type_}&key={$row_['uid']}&action=down&sorting={$row_['sorting']}'>{$image_down}</a></b>";
	$hide = "<b><a href='?id={$this->id}&item={$type_}&key={$row_['uid']}&action=hide'>{$image_hide}</a></b>";
	$edit = "<b><a href='?id={$this->id}&item={$type_}&key={$row_['uid']}&action=edit'>{$image_edit}</a></b>";

	return array($up, $down, $hide, $title_, $row_['description'], $row_['description_en'], $edit);
    }

    /**
     */
    function getButton($name) {
	$BACK_PATH = '../../../../typo3/';
	return '<img' . t3lib_iconWorks::skinImg($BACK_PATH, 'gfx/'.$name.'.gif','width="11" height="10" alt="'.$name.'"') . '>';
    }

    /** check whether all items are listet in the tx order table
     */
    function checkItemExistance($u_table_, $tx_table_, $item_name_)
    {
	print "DBG: checkItemExistance()<br />";
	print "Updating {$tx_table_}.{$item_name_} from table {$u_table_}<br />";
	// get all theses types and check whether they exist in the tx_ table
	$query = "SELECT DISTINCT `{$u_table_}`.`{$item_name_}` AS `{$item_name_}`, `{$tx_table_}`.`{$item_name_}` AS `tx_{$item_name_}` FROM `{$u_table_}`"
			. " LEFT OUTER JOIN `{$tx_table_}` ON `{$tx_table_}`.`{$item_name_}` = `{$u_table_}`.`{$item_name_}`"
			. " WHERE (`{$tx_table_}`.`{$item_name_}` = '' OR ISNULL(`{$tx_table_}`.`{$item_name_}`))";
	$rows = performSQLQuery($query);
	$newItemIds = array();
	if (count($rows) > 0) {
	    foreach($rows as $item) {
		$itemValue = $item[ $item_name_ ];
		echo "\t Adding {$item_name_} {$itemValue} ... ";
		$query = "INSERT INTO `{$tx_table_}`"
			    . " (`sorting`, `{$item_name_}`, `description`, `description_en`)"
			    . " VALUES"
			    . " (1000, '{$itemValue}', '{$itemValue}', '{$itemValue}')";
		$rv = performSQLQuery($query, false);
		if (true === $rv) {
		    $newItemIds[] = mysql_insert_id();
		}
		echo " done.<br />";
	    }
	    if (count($newItemIds) > 0) {
		print "Table {$tx_table_} is now up to date.<br />";
	    }
	} else {
	    print "Table {$tx_table_} was up to date.<br />";
	}
	return $newItemIds;
    }


    /**
     * @param $table_ string
     */
    function handleHide()
    {
	if (!@$_REQUEST['item'] || !@$_REQUEST['key'] || !@$_REQUEST['action']) {
	    return;
	}
	if ('hide' != @$_REQUEST['action']) {
	    return;
	}
	$query = "UPDATE `{$this->table_}`"
		. " SET `hidden` = (1 - `hidden`)"
		. " WHERE `uid` = {$_REQUEST['key']}";
	performSQLQuery($query, false);
    }

    /**
     * @param $table_ string
     */
    function handleSort()
    {
	if (!@$_REQUEST['item'] || !@$_REQUEST['key'] || !@$_REQUEST['action']) {
	    return;
	}
	if (! isset($_REQUEST['sorting']) ) {
	    return;
	}
	if ('up' == $_REQUEST['action'])
	{
	    $query = "SELECT MAX(`sorting`) AS `maxBelow`"
		. " FROM `{$this->table_}`"
		. " WHERE `sorting` <= {$_REQUEST['sorting']}"
		. " AND `uid` <> {$_REQUEST['key']}"
		. " LIMIT 1";
	    $rows = performSQLQuery($query);
	    $maxBelow = $rows[0]['maxBelow'];
	    if ($maxBelow > 0)
	    {
		$query = "UPDATE `{$this->table_}`"
			. " SET `sorting` = " . ($maxBelow + 1)
			. " WHERE `sorting` = {$maxBelow}";
		performSQLQuery($query, false);

		$query = "UPDATE `{$this->table_}`"
			. " SET `sorting` = " . $maxBelow
			. " WHERE `uid` = {$_REQUEST['key']}";
		performSQLQuery($query, false);
	    }
	}
	if ('down' == $_REQUEST['action'])
	{
	    $query = "SELECT MIN(`sorting`) AS `minAbove`"
		. " FROM `{$this->table_}`"
		. " WHERE `sorting` >= {$_REQUEST['sorting']}"
		. " AND `uid` <> {$_REQUEST['key']}"
		. " LIMIT 1";
	    $rows = performSQLQuery($query);
	    $minAbove = $rows[0]['minAbove'];
	    if ($minAbove > 0)
	    {
		$query = "UPDATE `{$this->table_}`"
			. " SET `sorting` = " . ($minAbove - 1)
			. " WHERE `sorting` = {$minAbove}";
		performSQLQuery($query, false);

		$query = "UPDATE `{$this->table_}`"
			. " SET `sorting` = " . $minAbove
			. " WHERE `uid` = {$_REQUEST['key']}";
		performSQLQuery($query, false);
	    }
	}
    }
}
?>
